package com.lsh.oms.worker.service.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dangdang.ddframe.job.api.JobExecutionMultipleShardingContext;
import com.dangdang.ddframe.job.plugin.job.type.dataflow.AbstractIndividualThroughputDataFlowElasticJob;
import com.lsh.base.common.model.CommonResult;
import com.lsh.base.common.utils.CollectionUtils;
import com.lsh.base.trace.id.filter.TraceIdSetter;
import com.lsh.ofc.api.dto.OrderDetailDTO;
import com.lsh.ofc.api.dto.OrderHeadDTO;
import com.lsh.ofc.api.service.OrderService;
import com.lsh.oms.api.model.es.OrderHeadForEs;
import com.lsh.oms.api.service.es.EsAsyncInterface;
import com.lsh.oms.core.enums.OrderOperateType;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.enums.StorageType;
import com.lsh.oms.core.model.order.OrderDetail;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.proxy.handler.OrderConcurrentHandler;
import com.lsh.oms.core.proxy.model.Position;
import com.lsh.oms.core.proxy.model.user.UserContent;
import com.lsh.oms.core.proxy.service.FenceServiceProxy;
import com.lsh.oms.core.proxy.service.MisProxy;
import com.lsh.oms.core.proxy.service.UserServiceProxy;
import com.lsh.oms.core.redis.RedisTemplate;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.order.OrderUpdateService;
import com.lsh.oms.worker.service.service.OrderCommit2OfcService;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 订单提交OFC
 *
 * @author huangdong
 * @date 17/1/8
 */
@Component
public class OrderCommit2OfcJob extends AbstractIndividualThroughputDataFlowElasticJob<OrderHead> implements InitializingBean {

    private final static String DELIVERY_WAY = "delivery_way";
    private final static String PRE_WAREHOUSE_CODE = "pre_warehouse_code";
    private static final String KEY_FULFILL_EXCLUDE_ORDER_CODES_PREFIX = "OMS_FULFILL_EXCLUDE_ORDER_CODES_";
    private static final String KEY_FULFILL_INCLUDE_ORDER_CODES_PREFIX = "OMS_FULFILL_INCLUDE_ORDER_CODES_";
    private static final String KEY_FULFILL_SALE_AREA_CODE_LOCK = "KEY_FULFILL_SALE_AREA_CODE_LOCK";
    private static final Integer ORDER_STATUS = OrderStatus.ORDER_COMMITING_OFC.getIndex();
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private OrderQueryService orderQueryService;
    @Autowired
    private OrderUpdateService orderUpdateService;
    @Autowired
    private OrderService ofcOrderService;
    @Autowired
    private EsAsyncInterface esAsyncInterface;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserServiceProxy userServiceProxy;
    @Autowired
    private FenceServiceProxy fenceServiceProxy;
    @Autowired
    private OrderCommit2OfcService orderCommit2OfcService;

    @Autowired
    private MisProxy misProxy;

    @Value("${shopUrl}")
    private String shopUrl;

    @Value("#{'${hold.order.dcs}'.split(',')}")
    private List<String> holdOrderDcs;

    @Value("${wumart.time}")
    private String wumartTime;

    @Value("${cloud.dc.time}")
    private String cloudDcTime;

    private ConcurrentMap<Integer, Set<Long>> excludeOrderCodesMap = new ConcurrentHashMap<>(4);

    @Override
    public void afterPropertiesSet() throws Exception {
    }


    /**
     * 删除错误记录
     *
     * @param orderCode
     */
    private void delErrorRecord(Integer regionCode, Long orderCode) {
        Set<Long> codes = this.excludeOrderCodesMap.get(regionCode);
        if (CollectionUtils.isEmpty(codes)) {
            return;
        }
        if (codes.contains(orderCode)) {
            this.redisTemplate.hdel(KEY_FULFILL_EXCLUDE_ORDER_CODES_PREFIX + regionCode, orderCode.toString());
        }
    }

    private long getCurrentMinute() {
        long ret = 0;
        Calendar cal = Calendar.getInstance();
        ret = cal.get(Calendar.YEAR) + ret;
        ret = cal.get(Calendar.MONTH) + 1 + ret * 100;
        ret = cal.get(Calendar.DATE) + ret * 100;
        ret = cal.get(Calendar.HOUR_OF_DAY) + ret * 100;
        ret = cal.get(Calendar.MINUTE) + ret * 100;
        return ret;
    }

    private boolean filterByTime(String[] params) {
        if (params == null || params.length <= 0) {
            return false;
        }
        long start = 0;
        long end = 0;
        String startStr = params[0];
        if (startStr != null && startStr.length() == 12) {
            start = NumberUtils.toLong(startStr, 0);
        }
        if (params.length >= 2) {
            String endStr = params[1];
            if (endStr != null && endStr.length() == 12) {
                end = NumberUtils.toLong(endStr, 0);
            }
        }
        long time = this.getCurrentMinute();
        if (start <= 0) {
            if (end <= 0) {
                return false;
            } else {
                return time < end;
            }
        } else {
            if (end <= 0) {
                return time >= start;
            } else {
                return time >= start && time <= end;
            }
        }
    }

    @Override
    public List<OrderHead> fetchData(JobExecutionMultipleShardingContext context) {
        TraceIdSetter.set();
        logger.info("订单提交OFC fetchData start..." + context.toString());
        String jobParameter = context.getJobParameter();
        if (StringUtils.hasLength(jobParameter) && this.filterByTime(jobParameter.split(";"))) {
            logger.info("订单提交OFC fetchData break by job unprocessable time range... param=" + jobParameter);
            return Collections.emptyList();
        }

        String saleAreaLock = this.getSaleAreaCodeLock();

        int fetchSize = context.getFetchDataCount();
        Map<Integer, String> items = context.getShardingItemParameters();
        List<OrderHead> orders = new ArrayList<>(items.size() * fetchSize);
        Set<Long> orderCodes = new HashSet<>();
        for (String param : items.values()) {
            String[] array = param.split(";");
            Integer regionCode = Integer.valueOf(array[0]);
            int timeOffset = Integer.parseInt(array[1]);
            String supplierGroupId = array[2];
            if (supplierGroupId.equals("0")) {
                supplierGroupId = null;
            }

            Set<Long> orderCodesTemp = this.getIncludeOrderCodes(regionCode);
            if (orderCodesTemp != null && orderCodesTemp.size() > 0) {
                logger.info("订单提交OFC fetchData(regionCode=" + regionCode + ", timeOffset=" + timeOffset + ") allow commit ofc codes:" + JSON.toJSONString(orderCodesTemp));
                orderCodes.addAll(orderCodesTemp);
            }

//            if (array.length > 2 && this.filterByTime(Arrays.copyOfRange(array, 2, 4))) {
//                logger.info("订单提交OFC fetchData(regionCode=" + regionCode + ", timeOffset=" + timeOffset + ") break by job unprocessable time range... param=" + param);
//                continue;
//            }

            Set<Long> excludeOrderCodes = this.getExcludeOrderCodes(regionCode);
            logger.info("订单提交OFC fetchData(regionCode=" + regionCode + ", timeOffset=" + timeOffset + ") start...");
            List<OrderHead> list = this.orderQueryService.findListByRegionAndStatus(null, ORDER_STATUS, excludeOrderCodes, timeOffset, fetchSize, saleAreaLock, 1, supplierGroupId);
            logger.info("订单提交OFC fetchData(regionCode=" + regionCode + ", timeOffset=" + timeOffset + ") end ... size=" + list.size());
            orders.addAll(list);
        }

        for (Long code : orderCodes) {
            OrderHead orderHead = this.orderQueryService.findByCode(code, false, false);
            if (orderHead != null && !orders.contains(orderHead)) {
                orders.add(orderHead);
            }
        }

        if (StringUtils.hasText(saleAreaLock)) {
            logger.info("订单提交OFC fetchData sale area lock:" + saleAreaLock);
            Iterator<OrderHead> iterator = orders.iterator();
            while (iterator.hasNext()) {
                OrderHead orderHead = iterator.next();
                if (!StringUtils.hasText(orderHead.getSaleAreaCode())) {
                    continue;
                }
                if (saleAreaLock.contains(orderHead.getSaleAreaCode()) && !orderCodes.contains(orderHead.getOrderCode())) {
                    iterator.remove();
                }
            }
        }

        logger.info("订单提交OFC fetchData end ... size=" + orders.size());
        return orders;
    }

    @Override
    public boolean processData(JobExecutionMultipleShardingContext context, OrderHead model) {
        boolean isExecuteStrategy = false;
        String jobParameter = context.getJobParameter();
        if (!StringUtils.isEmpty(jobParameter)) {
            isExecuteStrategy = jobParameter.equals("1");
        }

        if (model == null) {
            return false;
        }
        Integer regionCode = model.getRegionCode();
        Long orderCode = model.getOrderCode();
        if (orderCode == null) {
            return false;
        }

        if (OrderConcurrentHandler.isExists(orderCode)) {
            logger.info("订单提交OFC processData(" + orderCode + ") interrupt... 订单已经取消...");
            return false;
        }

        if (!OrderConcurrentHandler.lockOrder(orderCode)) {
            logger.info("订单提交OFC processData(" + orderCode + ") interrupt... 订单正在处理...");
            return false;
        }

        try {
            logger.info("订单提交OFC processData(" + orderCode + ") start...");
            if (!ORDER_STATUS.equals(model.getOrderStatus())) {
                logger.info("订单提交OFC processData(" + orderCode + ") end... 订单状态(" + model.getOrderStatus() + ")不是`" + OrderStatus.getName(ORDER_STATUS) + "`");
                return true;
            }

            // 如果是DC12,DC15,DC30,DC36,DC21物美仓的订单；
            // 下单时间，小于10：50实时下发；大于10：50，在次日03：00 ~ 10：50之间下发
            boolean flag = this.isFilterWumartOrder(model);
            logger.info("订单提交OFC processData(" + orderCode + ") 是否过滤物美订单：{}", flag);
            if (flag) {
                this.setExcludeOrderCodes(model.getRegionCode(), model.getOrderCode().toString());
                return true;
            }

            List<OrderDetail> details = this.orderQueryService.findDetails(orderCode);
            if (CollectionUtils.isEmpty(details)) {
                this.incrErrorTimes(regionCode, orderCode);
                logger.warn("订单提交OFC processData(" + orderCode + ") end... 订单明细为空");
                return false;
            }
            try {
                boolean ret = this.commitOfc("订单提交OFC processData(" + orderCode + ")", model, isExecuteStrategy);

                if (!ret) {
                    this.incrErrorTimes(regionCode, orderCode);
                    logger.warn("订单提交OFC processData(" + orderCode + ") end... 提交失败");
                    return true;
                }
                this.updateOrderStatus(model);
                this.delErrorRecord(regionCode, orderCode);
                logger.info("订单提交OFC processData(" + orderCode + ") end... 提交成功");
                return true;
            } catch (Throwable t) {
                logger.error("订单提交OFC processData(" + orderCode + ") end... 提交错误. error message:" + t.getMessage());
                throw t;
            }
        } finally {
            OrderConcurrentHandler.unlockOrder(orderCode);
        }
    }

    /**
     * 判断是否是DC12,DC15,DC30,DC36,DC21的订单，
     * 下单时间，小于10：50实时下发；
     * 大于10：50，在次日03：00 ~ 10：50之间下发
     *
     * @param orderHead
     * @return
     */
    private boolean isFilterWumartOrder(OrderHead orderHead) {
        JSONObject ext = JSONObject.parseObject(orderHead.getExt());

        if (ext != null && ext.size() > 0) {
            String orderDc = ext.getString("orderDc");

            if (!StringUtils.isEmpty(orderDc) && holdOrderDcs.contains(orderDc)) {
                if (StringUtils.isEmpty(wumartTime) || StringUtils.isEmpty(cloudDcTime)) {
                    return true;
                }

                String timeStr = wumartTime;
                if (orderDc.equals("LSx01")) {
                    timeStr = cloudDcTime;
                }

                String[] split = timeStr.split("~");
                if (split == null || split.length != 2) {
                    return true;
                }

                return this.compareTime(orderHead.getOrderCode().toString(), Long.valueOf(orderHead.getOrderTime()), split[0], split[1]);
            }
        }

        return false;
    }

    /**
     * 判断当前时间，是否在指定时间范围内
     *
     * @param orderCode
     * @param time
     * @param startStr
     * @param endStr
     * @return
     */
    private boolean compareTime(String orderCode, Long time, String startStr, String endStr) {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        try {
            // 下单时间
            Date date = df.parse(df.format(new Date(time * 1000L)));
            Calendar orderTime = Calendar.getInstance();
            orderTime.setTime(date);

            // hold结束时间
            Date startTime = df.parse(startStr);
            Calendar start = Calendar.getInstance();
            start.setTime(startTime);

            // hold单开始时间
            Date endTime = df.parse(endStr);
            Calendar end = Calendar.getInstance();
            end.setTime(endTime);

            // 系统当前时间
            Calendar now = Calendar.getInstance();
            now.setTime(df.parse(df.format(new Date())));

            // 判断，举例（03：00  < 下单时间 < 18：00）or（03：00  < 系统当前时间 < 18：00），订单释放，否则hold单
            return (orderTime.after(end) || orderTime.before(start)) && (now.before(start) || now.after(end));
        } catch (ParseException e) {
            logger.error("订单提交OFC processData(" + orderCode + ") 解析时间点异常", e);
            return true;
        }
    }

    /**
     * 提交OFC
     *
     * @param head
     * @return
     */
    private boolean commitOfc(String logSign, OrderHead head, boolean isExecuteStrategy) {
        Long orderCode = head.getOrderCode();
        // 如果是非自营, 则不需要履约
        if (!isExecuteStrategy && StorageType.LOW.getIndex() == head.getStorageType().intValue()) {
            logger.info("isProprietary(head) " + isProprietary(head));
            return false;
        }

        List<OrderDetail> details = this.orderQueryService.findDetails(orderCode);
        head.setDetails(details);
        if (CollectionUtils.isEmpty(details)) {
            return false;
        }
        JSONObject extJson = JSON.parseObject(head.getExt());
        String orderDc = extJson.getString("orderDc");
        JSONObject addressInfo = JSON.parseObject(head.getAddressInfo());

        if (StringUtils.isEmpty(head.getSupplierGroupId()) || head.getSupplierGroupId().equals("0")) {
            logger.info("addressInfo {} 履约用户组信息不存在", addressInfo);
            return false;
        }

        Integer logisticsMode = this.getLogisMode(head, logSign);
        if (null == logisticsMode) {
            logger.info("addressInfo {} 策略服务返回策略模式为空", addressInfo);
            return false;
        }

        String supplierGroup = userServiceProxy.getSupplierGroup(head.getAddressCode().toString(), head.getVenderId());

        logger.info("supplierGroup  dsdsd is " + supplierGroup);
        if (StringUtils.isEmpty(supplierGroup)) {
            logger.info("{} supplierGroupid [{}],请求商城用户信息异常", logSign, supplierGroup);
            return false;
        }

        if (0 == logisticsMode) {
            logger.info("orderCode {} 订单不需要提交ofc", orderCode);
            return false;
        }

        List<OrderDetailDTO> dtos = new ArrayList<>(details.size());
        for (OrderDetail orderDetail : details) {
            OrderDetailDTO dto = new OrderDetailDTO();
            dto.setDetailId(orderDetail.getId());
            dto.setItemCode(orderDetail.getItemCode());
            dto.setGoodsCode(orderDetail.getGoodsCode());
            dto.setGoodsName(orderDetail.getGoodsName());
            dto.setGoodsBarCode(orderDetail.getGoodsBarcode());
            dto.setGoodsType(orderDetail.getType());
            dto.setGoodsSaleUnit(orderDetail.getGoodsSaleUnit());
            dto.setGoodsPrice(orderDetail.getPrice());
            dto.setGoodsAmount(orderDetail.getPrice().multiply(orderDetail.getQuantity()));
            dto.setSkuCode(orderDetail.getSkuCode());
            dto.setSkuQty(orderDetail.getQuantity().multiply(orderDetail.getGoodsSaleUnit()));
            dto.setGoodsQty(orderDetail.getQuantity());

            JSONObject detailExt = JSON.parseObject(orderDetail.getDetailExt());
            Integer isWeighingGoods = detailExt.getInteger("isWeighingGoods");
            if (null == isWeighingGoods) {
                isWeighingGoods = 0;
            }
            dto.setIsWeighingGoods(isWeighingGoods);
            dto.setGoodsExtAttrs(orderDetail.getGoodsExtAttrs());
            dtos.add(dto);
        }
        OrderHeadDTO dto = new OrderHeadDTO();
        dto.setOrderCode(orderCode);
        dto.setRegionCode(head.getRegionCode());
        dto.setAddressCode(head.getAddressCode());
        dto.setAddressInfo(head.getAddressInfo());
        dto.setOrderAmount(head.getExpectPayAmount());
        dto.setCreateTime(head.getCreateTime());
        dto.setParentOrderCode(head.getParentOrderCode());
        dto.setVenderId(head.getVenderId());

        Integer providerId = extJson.getInteger("providerId");
        String providerName = extJson.getString("providerName");
        String parentHaveCloudChildren = extJson.getString("parentHaveCloudChildren");

        String poOrderFlag = extJson.getString("poOrderFlag");
        String poId = extJson.getString("poId");
        String supplierCode = extJson.getString("supplierCode");

        logger.info("commit to ofc " + providerId + ":providerName : " + providerName);
        if (providerId == null) {
            return false;
        }

        if (StringUtils.isEmpty(orderDc)) {
            return false;
        }

        dto.setProviderId(providerId);
        dto.setProviderName(providerName);
        dto.setOrderDc(orderDc);
        dto.setDetails(dtos);

        JSONObject orderExt = new JSONObject();
        orderExt.put("poOrderFlag", ObjectUtils.toString(poOrderFlag, "0"));
        orderExt.put("poId", ObjectUtils.toString(poId, ""));
        orderExt.put("supplierCode", ObjectUtils.toString(supplierCode, ""));
        orderExt.put("logisticsMode", logisticsMode);
        orderExt.put("orderClass", head.getOrderClass());

        String supplierGroupId = head.getSupplierGroupId();
        String dMallOrderType = addressInfo.getString("dMallOrderType");
        if(!StringUtils.isEmpty(dMallOrderType) && dMallOrderType.equals("2")){

            supplierGroupId = "0" + supplierGroupId;
        }

        orderExt.put("supplierGroupId", supplierGroupId);
        dto.setOrderExt(orderExt.toJSONString());
        if (StringUtils.isEmpty(parentHaveCloudChildren)) {
            parentHaveCloudChildren = "0";
        }

        dto.setParentHaveCloudChildren(parentHaveCloudChildren);

        logger.info("订单提交OFC processData(" + orderCode + ") 提交OFC开始，请求参数：" + JSON.toJSONString(dto));
        long start = System.currentTimeMillis();
        CommonResult<Boolean> resp = null;
        try {
            resp = this.ofcOrderService.createOrder(dto);
            long end = System.currentTimeMillis();
            logger.info("订单提交OFC processData(" + orderCode + ") 提交OFC结束，耗时：" + (end - start) + "ms，返回结果：" + JSON.toJSONString(resp));
        } catch (Exception e) {
            long end = System.currentTimeMillis();
            logger.error("订单提交OFC processData(" + orderCode + ") 提交OFC异常！，耗时：" + (end - start) + "ms。" + e.getMessage(), e);
        }
        if (resp == null) {
            return false;
        }
        if (CommonResult.SUCCESS.equals(resp.getCode()) && Boolean.TRUE.equals(resp.getData())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param head
     * @param logSign
     * @return
     */
    private Integer getLogisMode(OrderHead head, String logSign) {
        Long addressId = head.getAddressCode();
        JSONObject extJson = JSON.parseObject(head.getExt());
//        String orderDc = extJson.getString("orderDc");

        Integer logisticsModeDb = extJson.getInteger("logisticsMode");
        if (null != logisticsModeDb) {
            return logisticsModeDb;
        }

//        UserContent userContent = this.userServiceProxy.getUserInfo(String.valueOf(addressId), head.getVenderId());
//        if (null == userContent) {
//            logger.info("{} 地址id [{}],请求商城用户信息异常", logSign, addressId);
//            return null;
//        }

//        Position position = new Position();
//                this.orderCommit2OfcService.parsePosition(userContent.getAddressInfo());
//        if (position == null) {
//            logger.info("commitOfc false 地址id [{}],解析用户经纬度坐标错误", addressId);
//            return null;
//        }

        // 查询围栏服务，获取前置仓围栏信息

//                this.fenceServiceProxy.getFenceId(position, userContent.getAddressInfo().getCounty());
//        if (!this.orderCommit2OfcService.isCommitOfc(logSign, head, orderDc, userContent, fenceInfo)) {
//            logger.info("订单不需要提交ofc orderCode {}", head.getOrderCode());
//            return 0;
//        }
        Position position = new Position();
        Map<String, Object> fenceInfo = new HashMap<>();
        JSONObject addressInfo = new JSONObject();
        UserContent userContent = new UserContent();
        // 请求策略服务，决定订单物流模式
        Integer logisticsMode = this.orderCommit2OfcService.obtainOrderLogisticsMode(logSign, head, addressInfo, userContent, position, fenceInfo, head.getSupplierGroupId());

        return logisticsMode;

    }

    /**
     * 判断是否是自营, providerId为空,就是自营
     *
     * @param head
     * @return
     */
    private boolean isProprietary(OrderHead head) {
        String ext = head.getExt();
        JSONObject jsonObject = JSON.parseObject(ext);
        String providerId = jsonObject.getString("providerId");
        return StringUtils.isEmpty(providerId);
    }

    /**
     * 更新订单状态
     *
     * @param head
     * @return
     */
    private int updateOrderStatus(OrderHead head) {

        Long orderCode = head.getOrderCode();
        OrderStatus orderStatus = OrderStatus.ORDER_COMMITED_OFC;
        logger.info("订单提交OFC processData(" + orderCode + ") 更新订单状态开始！");
        int ret = this.orderUpdateService.updateOrderStatus(orderCode, null, OrderOperateType.ORDER_COMMITTED_TO_OFC, head.getVenderId());
        logger.info("订单提交OFC processData(" + orderCode + ") 更新订单状态结束！ret=" + ret);
        if (ret <= 0) {
            return 0;
        }

        //ElasticSearch同步订单状态
        OrderHeadForEs orderHeadForEs = new OrderHeadForEs();
        orderHeadForEs.setOrderCode(orderCode);
        orderHeadForEs.setOrderStatus(orderStatus.getIndex());
        logger.info("订单提交OFC processData(" + orderCode + ") 更新ES开始，请求参数：" + JSON.toJSONString(orderHeadForEs));
        try {
            esAsyncInterface.editIndex(orderHeadForEs);
            logger.info("订单提交OFC processData(" + orderCode + ") 更新ES结束！");
        } catch (Exception e) {
            logger.error("订单提交OFC processData(" + orderCode + ") 更新ES异常！" + e.getMessage(), e);
            return -1;
        }
        return ret;
    }

    /**
     * 获取需要排除的订单号
     *
     * @return
     */
    private Set<Long> getExcludeOrderCodes(Integer regionCode) {
        Map<String, String> map = this.redisTemplate.hgetAll(KEY_FULFILL_EXCLUDE_ORDER_CODES_PREFIX + regionCode);
        Set<Long> codes = new HashSet<>(map.size());
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (NumberUtils.toInt(entry.getValue()) >= 10) {
                codes.add(Long.valueOf(entry.getKey()));
            }
        }
        this.excludeOrderCodesMap.put(regionCode, codes);
        return codes;
    }

    /**
     * 获取需要排除的订单号
     *
     * @return
     */
    private void setExcludeOrderCodes(Integer regionCode, String orderCode) {
        try {
            this.redisTemplate.hsetnx(KEY_FULFILL_EXCLUDE_ORDER_CODES_PREFIX + regionCode, orderCode, "100");
        } catch (Exception e) {
            logger.error("订单提交OFC processData(" + orderCode + ") 操作redis异常", e);
        }
    }

    /**
     * 获取允许下发的订单号
     *
     * @return
     */
    private Set<Long> getIncludeOrderCodes(Integer regionCode) {
        Set<String> set = this.redisTemplate.smembers(KEY_FULFILL_INCLUDE_ORDER_CODES_PREFIX + regionCode);
        Set<Long> codes = new HashSet<>(set.size());
        for (String s : set) {
            this.redisTemplate.sremove(KEY_FULFILL_INCLUDE_ORDER_CODES_PREFIX + regionCode, s);
            codes.add(Long.valueOf(s));
        }
        return codes;
    }

    /**
     * 获取履约子区域锁
     *
     * @return
     */
    private String getSaleAreaCodeLock() {
        String lock = this.redisTemplate.get(KEY_FULFILL_SALE_AREA_CODE_LOCK);
        return lock;
    }


    /**
     * 增加错误次数
     *
     * @param orderCode
     */
    private void incrErrorTimes(Integer regionCode, Long orderCode) {
//        this.redisTemplate.hincr(KEY_FULFILL_EXCLUDE_ORDER_CODES_PREFIX + regionCode, orderCode.toString());
    }
}
